const config = require('../../../utils/config.js');
var QQMapWX = require('../../../utils/qqmap.js');
var qqMap = new QQMapWX({
  key: config.key
});
import api from '../../../common/api.js'
import { insertHouseLog } from '../../../common/log.js';
import constant from '../../../common/constant.js';
import * as transferData from '../../../models/transferData'
import locationBehavior from "../../../behaviors/location.js";


const app = getApp()
Page({
  behaviors: [locationBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    choosefloor: -1,
    rows: [],
    showCreat: false,
    keyWords: '',
    subscribe: false
  },
  //取消
  goRrevPage() {
    wx.navigateBack({
      detal: 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if( Number(options.subscribe)){
      this.setData({
        subscribe: true
      })
    }
    var currentCity = wx.getStorageSync('currentCity');
    insertHouseLog({
      logType: "2",
      cityName: currentCity ? currentCity.city : "上海市",
      inputHouseType: app.getCurrentStatusName()
    })

    if (options.choosefloor) {
      this.setData({
        choosefloor: options.choosefloor
      })
    }
    if (options.mainBuilding) {
      this.setData({
        mainBuilding: options.mainBuilding
      })
    }
  },
  goCreateHouse() {
    if (this.data.mainBuilding == 1) {
      wx.navigateTo({
        url: '/pages/addHouse/createHouse/createHouse?mainBuilding=1',
      })
    } else {
      wx.navigateTo({
        url: '/pages/addHouse/createHouse/createHouse?keywords=' + this.data.keyWords,
      })
    }
  },
  goInfoEntryHouse(e) {
    var that = this,

      villageData = e.currentTarget.dataset.village,
      mainBuilding = that.data.mainBuilding,
      nosearch = e.currentTarget.dataset.nosearch;
    // debugger
    wx.setStorageSync("resblockName", '1')
      // debugger
    if (mainBuilding == 1) {
      wx.setStorageSync("setState", true);
      if (nosearch && nosearch == 1) {
        api.addVillage({
          resblockName: villageData.title,
          addr: villageData.address,
          lng: villageData.location.lng,
          lat: villageData.location.lat,
        }, (res) => {
          // if (res.data.isSuccess) {
          var data = [{
            resblockId: res.data.content.id,
            hdResblockId: res.data.content.hdResblockId
          }];
          api.editResblock({
              resblock: JSON.stringify(data)
            }, res => {
              var loginUserInfo = getApp().globalData.loginUserInfo;
              if (loginUserInfo.data.content.sessionUser.extProps.resblock.length == 0) {
                loginUserInfo.data.content.sessionUser.extProps.resblock.push({});
              }
              loginUserInfo.data.content.sessionUser.extProps.resblock[0].city = res.data.content[0].city;
              loginUserInfo.data.content.sessionUser.extProps.resblock[0].area = res.data.content[0].area;
              wx.navigateBack({
                detal: 2
              })
            })
            // }
        })
      } else {
        var data = [{
          resblockId: villageData.resblockId,
          hdResblockId: villageData.hdResblockId
        }];
        api.editResblock({
          resblock: JSON.stringify(data)
        }, res => {
          var loginUserInfo = getApp().globalData.loginUserInfo;
          if (loginUserInfo.data.content.sessionUser.extProps.resblock.length == 0) {
            loginUserInfo.data.content.sessionUser.extProps.resblock.push({});
          }
          loginUserInfo.data.content.sessionUser.extProps.resblock[0].city = res.data.content[0].city;
          loginUserInfo.data.content.sessionUser.extProps.resblock[0].area = res.data.content[0].area;
          wx.navigateBack({
            detal: 2
          })
        })
      }
    } else {
      if (nosearch && nosearch == 1) {
        api.addVillage({
          resblockName: villageData.title,
          addr: villageData.address,
          lng: villageData.location.lng,
          lat: villageData.location.lat,
        }, (res) => {
          let villageData = {
            resblockName: res.data.content.resblockName,
            resblockId: res.data.content.id,
            addr: res.data.content.address,
          }

          let pageUrl = transferData.getData('selectHouseAreaEnterNextPage') || '/pages/addHouse/infoEntryHouse/infoEntryHouse';
          wx.navigateTo({
            url: `${pageUrl}?villageData=${JSON.stringify(villageData)}`
          })
          
          wx.gio('track', constant.CLICKS_SEARCH_RESULT, {
            [constant.SEARCHFROM_VAR]: constant.INPUT_SEARCH,
            [constant.SEARCHWORD_VAR]: that.data.keyWords,
            [constant.SEARCHSOURCE_VAR]: constant.XIAOQU_PAGE_SEARCH,
          })
        })
      } else {
        let pageUrl = transferData.getData('selectHouseAreaEnterNextPage') || '/pages/addHouse/infoEntryHouse/infoEntryHouse';
        wx.navigateTo({
          url: `${pageUrl}?villageData=${JSON.stringify(villageData)}`
        })

        wx.gio('track', constant.CLICKS_SEARCH_RESULT, {
          [constant.SEARCHFROM_VAR]: constant.INPUT_SEARCH,
          [constant.SEARCHWORD_VAR]: that.data.keyWords,
          [constant.SEARCHSOURCE_VAR]: constant.XIAOQU_PAGE_SEARCH,
        })
      }
    }
  },
  goFloorStrategy() {
    wx.navigateTo({
      url: '/pages/mine/floorStrategy/floorStrategy',
    })
  },
  //选择城市
  goSwitchCity() {
    wx.navigateTo({
      url: '/pages/home/switchCity/switchCity',
    })
  },
  //search keyWords 
  bindKeyInput(data) {
    var keyWords = data?data.detail.value:this.data.keyWords;
    var that = this;
    if (keyWords == '' || keyWords == ' ') {
      that.setData({
        rows: [],
        keyWords: ''
      })
    } else {
      api.villageList({
        resblockName: keyWords,
        pageNo: 1,
        rows: 10,
        city: that.data.currentCity && that.data.currentCity.city,
        isExternal: that.data.subscribe? true:null
      }, (res) => {
        console.log("小区搜索结束=========", res);
        if (res.data.isSuccess) {
          if(!that.data.subscribe){
            that.setData({
              keyWords: keyWords,
              rows: res.data.content.rows,
              records: res.data.content.records,
              loading: false,
              showCreat: true
            })
          }else {
            let rowId = [];
            let subscribeRow = res.data.content.rows;
            subscribeRow.map(v => rowId.push(v.hdResblockId))
            api.subscribeList(rowId, rev=> {
              let contentId = rev.data.content;
              subscribeRow.map(n => {
                let isSubscribe = contentId.find(o => {
                  return o== n.hdResblockId
                })
                if(isSubscribe){
                  n.subscribe = true
                } else {
                  n.subscribe = false
                }
                that.setData({
                  keyWords: keyWords,
                  rows: subscribeRow,
                  records: res.data.content.records,
                  loading: false,
                  showCreat: true
                })
              })
            })
          }
          if (res.data.content.records < 10) {
            that.mapSearchList();
          }

          insertHouseLog({
            logType: "3",
            cityName: that.data.currentCity && that.data.currentCity.city,
            inputHouseType: app.getCurrentStatusName(),
            searchContent: that.data.keyWords,
            resultNum: res.data.content.rows.length
          })

          wx.gio('track', constant.SEARCH_SUCCESS, {      
            [constant.SEARCHFROM_VAR]: constant.INPUT_SEARCH,
            [constant.IFSEARCHRESULT_VAR]: !!res.data.content.rows.length,
            [constant.SEARCHWORD_VAR]: that.data.keyWords,
            [constant.SEARCHSOURCE_VAR]: constant.XIAOQU_PAGE_SEARCH,
          })
        }
      })
    }
  },
  mapSearchList() {
    var that = this;
    qqMap.getSuggestion({
      keyword: that.data.keyWords,
      region: that.data.currentCity && that.data.currentCity.city,
      region_fix: 1,
      success: function(res) {
        that.setData({
          mapSearchList: res.data
        })
      },
      fail: function(res) {
      },

    });
  },
  getSubscribe(e){
    let sub = e.currentTarget.dataset.sub;
    let hdResblockId = e.currentTarget.dataset.hdresblockid;
    api.subscribe({
      hdResblockId,
      stated: sub,
    }, res => {
      transferData.setData('isRefreshMySubscribe', true)
      this.bindKeyInput()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.setStorageSync('lufangtiaozhuan', 1)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    this.getCityInfoNew().then((res) => {
      this.setData({
        currentCity: res,
      });
    })

    if (that.data.keyWords == '' || that.data.keyWords == ' ') {
      that.setData({
        rows: [],
        keyWords: ''
      })
    } else {
      api.villageList({
        resblockName: that.data.keyWords,
        pageNo: 1,
        rows: 10,
        city: that.data.currentCity && that.data.currentCity.city
      }, (res) => {
        if (res.data.isSuccess) {
          if(!that.data.subscribe){
            that.setData({
              keyWords: that.data.keyWords,
              rows: res.data.content.rows,
              records: res.data.content.records,
              loading: false,
              showCreat: true
            })
          }else {
            let rowId = [];
            let subscribeRow = res.data.content.rows;
            subscribeRow.map(v => rowId.push(v.hdResblockId))
            api.subscribeList(rowId, rev=> {
              let contentId = rev.data.content;
              subscribeRow.map(n => {
                let isSubscribe = contentId.find(o => {
                  return o== n.hdResblockId
                })
                if(isSubscribe){
                  n.subscribe = true
                } else {
                  n.subscribe = false
                }
                this.setData({
                  keyWords: that.data.keyWords,
                  rows: subscribeRow,
                  records: res.data.content.records,
                  loading: false,
                  showCreat: true
                })
              })
            })
          }
          if (res.data.content.records < 10) {
            that.mapSearchList();
          }

          insertHouseLog({
            logType: "3",
            cityName: that.data.currentCity && that.data.currentCity.city,
            inputHouseType: app.getCurrentStatusName(),
            searchContent: that.data.keyWords,
            resultNum: res.data.content.rows.length
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
})